package swu.myt;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet{
	
	private static final long serialVersionUID = 5050620068471180020L;
	
	public void init() {
		System.out.println("LoginServlet inilialized!");
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String username = request.getParameter("name");
		String pass = request.getParameter("pass");
		String code = request.getParameter("code");//得到参数
		HttpSession session=request.getSession(true);//获取session,如果session不存在，就新建一个
		
		String validateCode = (String)session.getAttribute(MyFilter.LOGIN_VALIDATE_CODE);//得到验证码的真实值
		if(validateCode == null || !validateCode.equalsIgnoreCase(code)){//用户输入的验证码不存在或不匹配
			response.sendRedirect("./index.jsp");//回到原界面
			System.out.println("this is loginServlet and validatecode not right!");
			return;
		}
		//到这里验证码验证成功，没成功不会继续下面的验证
		if(username!=null&&pass!=null&&validateCode != null) {
			try {
				if(UserCheck.findUser(username,pass)==true){//用户名密码正确（用数据库）
					session.setAttribute(MyFilter.LOGIN_STATUS, Boolean.TRUE);//登陆状态为真
					session.setAttribute("username", username);
					System.out.println("this is loginServlet and it return ok!");
					response.sendRedirect("./enter/userhome.jsp");//进入登陆后的界面
				}
				else {
					System.out.println("this is loginServlet and it return not ok!");
					response.sendRedirect("./index.jsp");//返回原界面
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
